<?php

namespace App\Library;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;

class KuaiDi
{
    public static function query(Model $logistics): array
    {
        //====================================
        // 实时查询示例代码
        // 授权信息可通过链接查看：https://api.kuaidi100.com/manager/v2/myinfo/enterprise
        //====================================
        $kd = __('logistics');
        $data = [
            'customer' => $kd['customer'],
            'param' => json_encode([
                'com' => $logistics->express_id, //快递公司编码
                'num' => $logistics->express_no, //快递单号
                'phone' => '',     //手机号
                'from' => '',                    //出发地城市
                'to' => '',          //目的地城市
                'resultv2' => '1',               //开启行政区域解析
                'show' => '0',                   //返回格式：0：json格式（默认），1：xml，2：html，3：text
                'order' => 'desc'                //返回结果排序:desc降序（默认）,asc 升序
            ], JSON_UNESCAPED_UNICODE),
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $kd['logistics']);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array_merge($data, [
            'sign' => strtoupper(md5($data['param'] . $kd['key'] . $kd['customer'])),
        ])));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        return json_decode(curl_exec($ch), true);
    }

    /**
     *
     * @param string $expressNo
     * @return JsonResponse|mixed
     * @throws GuzzleException
     *
     */
    public static function ExpressCodeInfo(string $expressNo): mixed
    {
        $client = new Client();
        $response = $client->get(sprintf(__('logistics.url'), $expressNo, __('logistics.key')));
        $info = json_decode($response->getBody(), true);
        if (empty($info[0]['comCode'])) {
            return response()->json([
                'code' => 200,
                'data' => [
                    'expressNo' => $expressNo,
                    'info' => null,
                    'message' => '物流公司获取失败'
                ]
            ]);
        } else return $info;
    }

    /**
     * @throws GuzzleException
     */
    public static function newQuery(string $expressCode, string $expressNo, string $mobile = null)
    {
        $paramJson = json_encode([
            'com' => $expressCode,  //快递公司编码
            'num' => $expressNo, //快递单号
            'phone' => $mobile
        ], JSON_UNESCAPED_UNICODE);

        $postData['customer'] = __('logistics.customer');
        $postData['param'] = $paramJson;
        $postData['sign'] = strtoupper(md5($paramJson . __('logistics.key') . __('logistics.customer')));

        $client = new Client();
        $response = $client->post(__('logistics.logistics') . '?' . http_build_query($postData));
        return json_decode($response->getBody(), true);
    }
}
